package gitee.derumin.lib_for_derumin.helpers.config.configserializers;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import net.minecraft.util.JsonHelper;

import java.nio.file.Path;

public class PathSerializer implements ConfigFieldSerializer<Path> {
    @Override
    public Path jsonToObject(JsonElement element, String name) {
        try {
            Path rootPath = Path.of(".\\");
            Path path = Path.of(JsonHelper.asString(element, name)).normalize();
            if (!path.startsWith(rootPath)){
                return rootPath.resolve(path);
            }else {
                return path;
            }
        }catch (Exception e){
            throw new JsonSyntaxException(name + "is not a valid path");
        }
    }

    @Override
    public JsonElement objectToJson(Object contains) {
        return new JsonPrimitive(((Path) contains).toString());
    }
}
